package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author junyong
 * @since 2024-8-4
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        // 1.从redis中查缓存
        List<String> list = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        // 2.判断是否存在
        if(list != null && list.size() != 0){
            // 3.存在，直接返回
            List<ShopType> shopTypeList = new ArrayList<>();
            list.forEach(shopType -> shopTypeList.add(JSONUtil.toBean(shopType, ShopType.class)));
            return Result.ok(shopTypeList);
        }
        // 4.不存在，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        // 5.不存在，返回错误
        if(shopTypeList == null || shopTypeList.size() == 0){
            return Result.fail("查询店铺类型不存在!");
        }
        // 6.存在，写入redis
        List<String> list1 = new ArrayList<>();
        shopTypeList.forEach(shopType -> list1.add(JSONUtil.toJsonStr(shopType)));
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_KEY, list1);
        // 7.返回
        return Result.ok(shopTypeList);
    }
}
